﻿using Forum.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Forum.Service.ForumHub
{
    [Authorize]
    public class ChatHub : Hub
    {
        public static List<HubUser> users = new List<HubUser>();
        protected readonly ILogger<ChatHub> _logger;
        public ChatHub(ILogger<ChatHub> logger)
        {
            _logger = logger;
        }
        /*
        /// <summary>
        /// 重写链接
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            int Count = 0;
            Interlocked.Increment(ref Count);

            base.OnConnectedAsync();
            Clients.All.SendAsync("updateCount", Count);
            Clients.All.SendAsync("connected", Context.ConnectionId);
            return Task.CompletedTask;
        }

        public async Task SendMessage(string msg, string connectId)
        {
            await Clients.Client(connectId).SendAsync("ReceiveMsg", "curry：" + msg + Environment.NewLine);
        }
        */

        //给指定用户发送消息
        public void SendMessage(string userId, string message)
        {
            //TODO: 增加用户分组，若客户发送消息后服务人员都不在线，需要给出提示，若存在服务人员，需要给对应组里的服务人员发送消息


            var user = users.Where(s => s.Id == userId).FirstOrDefault();
            if (user != null)
            {
                //Clients.Client(user.ConnectionID).SendAsync("ReceiveMsg", message + "" + DateTime.Now, Context.ConnectionId);
                //给自己发送，把用户的ID传给自己
                Clients.Client(Context.ConnectionId).SendAsync("ReceiveMsg", user.Name + "：" + message + " " + DateTime.Now + Environment.NewLine, user.ConnectionID);
            }
            else
            {
                Clients.Client(Context.ConnectionId).SendAsync("ReceiveMsg", "该用户已离线...");
            }
        }

        /// <summary>
        /// 重写连接事件
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            //根据链接Id查询用户
            var user = users.Where(u => u != null && u.ConnectionID == Context.ConnectionId).SingleOrDefault();
            if (user == null)
            {
                user = new HubUser(CurrentUser.UserName, CurrentUser.UserId, Context.ConnectionId);
                users.Add(user);
            }
            return base.OnConnectedAsync();
        }

        [AllowAnonymous]
        /// <summary>
        /// 重写断开连接事件
        /// </summary>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            var user = users.Where(p => p.ConnectionID == Context.ConnectionId).FirstOrDefault();
            //判断用户是否存在，存在则删除
            if (user != null)
            {
                //删除用户
                users.Remove(user);
            }
            await base.OnDisconnectedAsync(exception);
        }

        public async Task UpdateData(object data)
        {
            string connectionId = string.Empty;
            //给所有人发消息
            await Clients.All.SendAsync("客户端接收方法", data);
            //分组（users）发消息
            await Clients.Group("users").SendAsync("客户端接收方法", data);
            //给调用方法的人发送消息
            await Clients.Caller.SendAsync("客户端接收方法", data);
            //给除了调用方以外的人发消息
            await Clients.Others.SendAsync("客户端接收方法", data);
            //给指定connectionId的人发送消息
            await Clients.User(connectionId).SendAsync("客户端接收方法", data);
            await Clients.Client(connectionId).SendAsync("客户端接收方法", data);

            //给多个指定connectionId的人发送消息
            string connectionId1 = string.Empty;
            string connectionId2 = string.Empty;
            await Clients.Clients(connectionId, connectionId1, connectionId2).SendAsync("客户端接收方法", data);
        }


    }

    public class HubUser
    {
        /// <summary>
        /// 连接ID
        /// </summary>
        [Key]
        public string ConnectionID { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 用户id
        /// </summary>
        public string Id { get; set; }

        public HubUser(string name, string id, string connectionId)
        {
            Name = name;
            Id = id;
            ConnectionID = connectionId;
        }
    }
}
